package com.xbfinal.eduservice.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbfinal.commonUtils.Exception.GuliException;
import com.xbfinal.eduservice.entity.EduSubject;
import com.xbfinal.eduservice.entity.excel.subjectData;
import com.xbfinal.eduservice.service.EduSubjectService;

import java.util.Map;

/**
 * @Title: SubjectReadListener
 * @Author 笑霸fianl
 * @Package com.xbfinal.eduservice.listener
 * @Date 2023/1/5 9:46
 * @描述: 有个很重要的点 DemoDataListener 不能被spring管理，
 * 要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 */
public class SubjectReadListener extends AnalysisEventListener<subjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectReadListener(){};

    public SubjectReadListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }


    /**
     * 读取内容
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(subjectData subjectData, AnalysisContext analysisContext) {

        if(subjectData == null){
            throw new GuliException(20001,"文件为空");
        }
        //判断1级方法是否重复
        EduSubject oneExist = this.oneExist(eduSubjectService, subjectData.getOneSubjectName());
        if(BeanUtil.isEmpty(oneExist)){
            //为空 表示没有相同的一级分类 就添加
            oneExist = new EduSubject();
            oneExist.setParentId("0");
            oneExist.setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(oneExist);
        }

        //添加二级分类
        String pid=oneExist.getId();
        EduSubject twoExist = this.twoExist(eduSubjectService, subjectData.getTwoSubjectName(),pid);
        if(BeanUtil.isEmpty(twoExist)){
            //为空 表示没有相同的一级分类 就添加
            twoExist = new EduSubject();
            twoExist.setParentId(pid);
            twoExist.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(twoExist);
        }

    }

    /**
     * 判断一级分类不能重复添加
     *
     */
    private EduSubject oneExist(EduSubjectService eduSubjectService, String name){

        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;

    }


    /**
     * 判断二级分类不能重复添加
     *
     */
    private EduSubject twoExist(EduSubjectService eduSubjectService, String name,String pid){

        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;

    }




    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
